'''
Created on Dec 16, 2010

@author: mwicat
'''

import logging
logger = logging.getLogger(__name__)

CMD_PREFIX = 'sniffy '

import smswatch
import core
import shell
from core import SniffyCmd

class SmsSocketService(core.BaseRPCService):
    
    def __init__(self, shell, prefix=CMD_PREFIX):
        core.BaseRPCService.__init__(self, shell)
        self.prefix = prefix
        self.engine = smswatch.SMSEngine(self.handle)
        self.cmd_handler = None
        
    def strip_prefix(self, msg):
        pfx_len = len(self.prefix)
        msg = msg[pfx_len:]
        return msg
        
    def handle(self, msg, src):
        logger.debug('handling sms from %s: %s' % (src, msg))
        msg = self.strip_prefix(msg)
        name, params = core.parse_cmdln(msg)
        cmd = SniffyCmd(src, name, params)
        self.dispatch_cmd(cmd)
    
    def start_service(self):
        logger.debug('starting sms service...')
        self.engine.start_listening(self.prefix)

    def stop_service(self):
        self.engine.stop_listening()
